package io.github.wanggit.antrpc.gateway.web.utils;

import io.github.wanggit.antrpc.gateway.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public abstract class StreamUtil {

    public static String requestBodyToString(HttpServletRequest servletRequest) {
        if (isApplicationJson(servletRequest.getHeader(Constants.CONTENT_TYPE))) {
            try {
                byte[] bytes = IOUtils.toByteArray(servletRequest.getInputStream());
                return new String(bytes, StandardCharsets.UTF_8);
            } catch (IOException e) {
                if (log.isWarnEnabled()) {
                    log.warn("Read content ServletRequest");
                }
            }
        }
        return null;
    }

    public static boolean isApplicationJson(String contentType) {
        return contentType.toLowerCase().startsWith(Constants.APPLICATION_JSON);
    }
}
